<template>
  <div>
    <el-card style="width: 100%; height: 100%">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">物料管理</el-breadcrumb-item>
        <el-breadcrumb-item>产品管理</el-breadcrumb-item>
        <el-breadcrumb-item>产品信息管理</el-breadcrumb-item>
        <el-breadcrumb-item>产品信息管理列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card style="width: 100%; height: 100%; margin-top: 5px">
      <el-form :inline="true" :model="queryForm" label-width="auto">
        <el-form-item label="产品编号">
          <el-input
            v-model="queryForm.productCode"
            placeholder="请输入产品编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input
            v-model="queryForm.productName"
            placeholder="请输入产品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="产品类型" style="width: 250px;">
          <el-select
            style="width: 200px;"
            v-model="queryForm.productType"
            placeholder="请选择产品类型"
            clearable
          >
            <el-option
            style="width: 200px;"
              v-for="item in productTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-dropdown>
            <el-button type="info">
              更多
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleExport">导出全部</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
      <div style="margin-top: 10px">
        <el-button type="success" plain @click="handleAdd">新增+</el-button>
        <el-button type="warning" plain @click="handleImport">导入</el-button>
        <el-button type="primary" plain @click="handleExport">导出</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
      <el-table
        style="width: 100%; margin-top: 10px"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
        :loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="70" />
        <el-table-column prop="productCode" label="产品编号" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="specification" label="规格型号" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="productTypeLabel" label="产品类型" />
        <el-table-column prop="productAttributeLabel" label="产品属性" />
        <el-table-column prop="productCategoryLabel" label="产品分类" />
        <el-table-column prop="statusLabel" label="状态" width="90" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <table style="margin-top: 10px; width: 100%">
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[1, 2, 3, 5]"
              background
              layout="slot,total,sizes"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </td>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="slot,prev, pager"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              prev-text="上一页"
            >
              <template #default>
                <el-button type="primary" link @click="handleCurrentChange(1)">
                  首页
                </el-button>
              </template>
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="next,slot,jumper"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              next-text="下一页"
            >
              <template #default>
                <el-button
                  type="primary"
                  link
                  @click="handleCurrentChange(pagination.pageCount || 1)"
                >
                  尾页
                </el-button>
              </template>
            </el-pagination>
          </td>
        </tr>
      </table>
    </el-card>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="auto"
        style="max-width: 560px"
      >
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="formModel.productCode" placeholder="请输入产品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="formModel.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="formModel.specification" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formModel.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-select v-model="formModel.productType" placeholder="请选择产品类型">
                <el-option
                  v-for="item in productTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品属性" prop="productAttribute">
              <el-select v-model="formModel.productAttribute" placeholder="请选择产品属性">
                <el-option
                  v-for="item in productAttributeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="产品分类" prop="productCategory">
              <el-select v-model="formModel.productCategory" placeholder="请选择产品分类">
                <el-option
                  v-for="item in productCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formModel.status" placeholder="请选择状态">
                <el-option
                  v-for="item in statusOptions"
                  :key="String(item.value)"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formModel.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSubmit">保存</el-button>
          <el-button type="primary" @click="dialogVisible = false">取消</el-button>
          <el-button type="warning" @click="handleResetForm">重置</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight, ArrowDown } from "@element-plus/icons-vue";
import https from "@/Http/http";
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { useRouter } from "vue-router";

// 写库 API 基础地址（也可以直接使用 https.Writes 实例）
const WRITE_API_BASE = "http://localhost:5214";

// 后端DTO接口
interface ProductDTO {
  id: number;
  productcard: string;
  productname: string;
  productmodelsame: string;
  productunit: string;
  producttypeid: number;
  productattributeid: number;
  productclassificationid: number;
  productstate: boolean;
  productdays: number;
  productstopdays: number;
  productupper: number;
  productdown: number;
  productmoney: number;
  productdes: string;
  productphoto: string;
  productfile: string;
}

// 前端显示用的接口
interface ProductRow {
  id: number;
  productCode: string;
  productName: string;
  specification: string;
  unit: string;
  productType: number | null;
  productAttribute: number | null;
  productCategory: number | null;
  status: boolean;
  remark?: string;
  // 后端字段（用于编辑时）
  producttypeid?: number;
  productattributeid?: number;
  productclassificationid?: number;
  productstate?: boolean;
  productdes?: string;
  productdays?: number;
  productstopdays?: number;
  productupper?: number;
  productdown?: number;
  productmoney?: number;
  productphoto?: string;
  productfile?: string;
}

interface ProductTableRow extends ProductRow {
  index: number;
  productTypeLabel: string;
  productAttributeLabel: string;
  productCategoryLabel: string;
  statusLabel: string;
}

// API响应接口
interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: number;
  msg: string;
  data: T;
}

const loading = ref(false);
const tableData = ref<ProductTableRow[]>([]);
const multipleSelection = ref<ProductRow[]>([]);

const queryForm = reactive({
  productCode: "",
  productName: "",
  productType: null as number | null,
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

// 产品类型选项（这里需要根据实际业务从API获取，暂时使用示例数据）
const productTypeOptions = [
  { label: "类型一", value: 1 },
  { label: "类型二", value: 2 },
  { label: "类型三", value: 3 },
];

// 产品属性选项
const productAttributeOptions = [
  { label: "自制", value: 1 },
  { label: "外购", value: 2 },
];

// 产品分类选项
const productCategoryOptions = [
  { label: "分类一", value: 1 },
  { label: "分类二", value: 2 },
  { label: "分类三", value: 3 },
];

// 状态选项
const statusOptions = [
  { label: "启用", value: true },
  { label: "停用", value: false },
];

const productTypeMap = computed(() =>
  productTypeOptions.reduce<Record<number, string>>((acc, cur) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {})
);

const productAttributeMap = computed(() =>
  productAttributeOptions.reduce<Record<number, string>>((acc, cur) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {})
);

const productCategoryMap = computed(() =>
  productCategoryOptions.reduce<Record<number, string>>((acc, cur) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {})
);

const statusMap = computed(() =>
  statusOptions.reduce<Record<string, string>>((acc, cur) => {
    acc[String(cur.value)] = cur.label;
    return acc;
  }, {})
);

const router = useRouter();

// 将后端DTO转换为前端显示格式
const dtoToRow = (dto: ProductDTO, index: number): ProductTableRow => {
  return {
    id: dto.id,
    productCode: dto.productcard || "",
    productName: dto.productname || "",
    specification: dto.productmodelsame || "",
    unit: dto.productunit || "",
    productType: dto.producttypeid,
    productAttribute: dto.productattributeid,
    productCategory: dto.productclassificationid,
    status: dto.productstate,
    remark: dto.productdes || "",
    index,
    productTypeLabel: productTypeMap.value[dto.producttypeid] || `类型${dto.producttypeid}`,
    productAttributeLabel: productAttributeMap.value[dto.productattributeid] || `属性${dto.productattributeid}`,
    productCategoryLabel: productCategoryMap.value[dto.productclassificationid] || `分类${dto.productclassificationid}`,
    statusLabel: statusMap.value[String(dto.productstate)] || "--",
    // 保留后端字段用于编辑
    producttypeid: dto.producttypeid,
    productattributeid: dto.productattributeid,
    productclassificationid: dto.productclassificationid,
    productstate: dto.productstate,
    productdes: dto.productdes,
    productdays: dto.productdays,
    productstopdays: dto.productstopdays,
    productupper: dto.productupper,
    productdown: dto.productdown,
    productmoney: dto.productmoney,
    productphoto: dto.productphoto,
    productfile: dto.productfile,
  };
};

// 将前端表单数据转换为后端请求格式
const rowToRequest = (row: ProductRow) => {
  return {
    id: row.id || 0,
    productcard: row.productCode,
    productname: row.productName,
    productmodelsame: row.specification,
    productunit: row.unit,
    producttypeid: row.productType || row.producttypeid || 0,
    productattributeid: row.productAttribute || row.productattributeid || 0,
    productclassificationid: row.productCategory || row.productclassificationid || 0,
    productstate: row.status !== undefined ? row.status : (row.productstate !== undefined ? row.productstate : true),
    productdays: row.productdays || 0,
    productstopdays: row.productstopdays || 0,
    productupper: row.productupper || 0,
    productdown: row.productdown || 0,
    productmoney: row.productmoney || 0,
    productdes: row.remark || row.productdes || "",
    productphoto: row.productphoto || "",
    productfile: row.productfile || "",
  };
};

// 获取列表数据
const fetchTableData = () => {
  loading.value = true;
  const params: any = {
    pageindex: pagination.pageIndex,
    pagesize: pagination.pageSize,
  };

  // 添加查询条件
  // 产品编号或产品名称都映射到productname参数（后端API支持通过名称/编号搜索）
  if (queryForm.productCode || queryForm.productName) {
    params.productname = queryForm.productCode || queryForm.productName;
  }
  if (queryForm.productType !== null) {
    params.producttypeid = queryForm.productType;
  }

  https.Reads
    .get<ApiPageingResponse<ProductDTO>>(`/Product/ProductGetList`, {
      params,
    })
    .then((res) => {
      const response = res.data;
      if (response.code === 1) {
        tableData.value = (response.data || []).map((item, index) =>
          dtoToRow(item, (pagination.pageIndex - 1) * pagination.pageSize + index + 1)
        );
        pagination.totalCount = response.totalCount || 0;
        pagination.pageCount = response.pageCount || 0;
      } else {
        ElMessage.error(response.msg || "获取数据失败");
        tableData.value = [];
        pagination.totalCount = 0;
        pagination.pageCount = 0;
      }
    })
    .catch((error) => {
      console.error("获取数据失败:", error);
      ElMessage.error("获取数据失败，请稍后再试");
      tableData.value = [];
      pagination.totalCount = 0;
      pagination.pageCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  fetchTableData();
});

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  fetchTableData();
};

const handleSelectionChange = (val: ProductRow[]) => {
  multipleSelection.value = val;
};

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.productCode = "";
  queryForm.productName = "";
  queryForm.productType = null;
  handleQuery();
};

const handleImport = () => {
  ElMessage.info("导入功能待实现");
};

const handleExport = () => {
  ElMessage.info("导出功能待实现");
};

const formRef = ref<FormInstance>();
const dialogVisible = ref(false);
const dialogTitle = ref("");

const defaultFormModel: ProductRow = {
  id: 0,
  productCode: "",
  productName: "",
  specification: "",
  unit: "",
  productType: null,
  productAttribute: null,
  productCategory: null,
  status: true,
  remark: "",
  productdays: 0,
  productstopdays: 0,
  productupper: 0,
  productdown: 0,
  productmoney: 0,
};

const formModel = reactive<ProductRow>({ ...defaultFormModel });

const rules = reactive<FormRules>({
  productCode: [{ required: true, message: "产品编号不可为空", trigger: "blur" }],
  productName: [{ required: true, message: "产品名称不可为空", trigger: "blur" }],
  specification: [{ required: true, message: "规格型号不可为空", trigger: "blur" }],
  unit: [{ required: true, message: "单位不可为空", trigger: "blur" }],
  productType: [{ required: true, message: "请选择产品类型", trigger: "change" }],
  productAttribute: [{ required: true, message: "请选择产品属性", trigger: "change" }],
  productCategory: [{ required: true, message: "请选择产品分类", trigger: "change" }],
});

const handleAdd = () => {
  router.push("/ProductAdd");
};

const handleEdit = (row: ProductTableRow) => {
  dialogTitle.value = "产品信息编辑";
  // 将表格行数据转换为表单数据
  Object.assign(formModel, {
    id: row.id,
    productCode: row.productCode,
    productName: row.productName,
    specification: row.specification,
    unit: row.unit,
    productType: row.productType,
    productAttribute: row.productAttribute,
    productCategory: row.productCategory,
    status: row.status,
    remark: row.remark,
    // 保留后端字段
    producttypeid: row.producttypeid,
    productattributeid: row.productattributeid,
    productclassificationid: row.productclassificationid,
    productstate: row.productstate,
    productdes: row.productdes,
    productdays: row.productdays,
    productstopdays: row.productstopdays,
    productupper: row.productupper,
    productdown: row.productdown,
    productmoney: row.productmoney,
    productphoto: row.productphoto,
    productfile: row.productfile,
  });
  dialogVisible.value = true;
};

const handleResetForm = () => {
  Object.assign(formModel, defaultFormModel);
};

const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (!valid) {
      return;
    }

    const requestData = rowToRequest(formModel);
    const isEdit = formModel.id > 0;
    const url = isEdit
      ? `/Product/ProductUpdate`
      : `/Product/ProductAdd`;
    const method = isEdit ? "put" : "post";

    https.Writes[method]<ApiResultResponse<number>>(url, requestData)
      .then((res) => {
        const response = res.data;
        if (response.code === 1) {
          ElMessage.success(response.msg || "操作成功");
          dialogVisible.value = false;
          fetchTableData();
        } else {
          ElMessage.error(response.msg || "操作失败");
        }
      })
      .catch((error) => {
        console.error("操作失败:", error);
        ElMessage.error("请求失败，请稍后再试");
      });
  });
};

const handleDelete = (row: ProductRow) => {
  ElMessageBox.confirm("确认删除当前产品信息吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes
        .delete<ApiResultResponse<number>>(`/Product/ProductDel`, {
          data: { id: row.id },
        })
        .then((res) => {
          const response = res.data;
          if (response.code === 1) {
            ElMessage.success(response.msg || "删除成功");
            fetchTableData();
          } else {
            ElMessage.error(response.msg || "删除失败");
          }
        })
        .catch((error) => {
          console.error("删除失败:", error);
          ElMessage.error("删除失败，请稍后再试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的产品");
    return;
  }
  ElMessageBox.confirm(`确认批量删除所选 ${multipleSelection.value.length} 个产品吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 由于没有批量删除接口，循环调用单个删除接口
      const deletePromises = multipleSelection.value.map((item) =>
        https.Writes.delete<ApiResultResponse<number>>(`/Product/ProductDel`, {
          data: { id: item.id },
        })
      );

      Promise.all(deletePromises)
        .then((results) => {
          const successCount = results.filter((res) => res.data.code === 1).length;
          if (successCount === multipleSelection.value.length) {
            ElMessage.success(`成功删除 ${successCount} 个产品`);
            fetchTableData();
          } else {
            ElMessage.warning(`部分删除成功，成功 ${successCount} 个，失败 ${multipleSelection.value.length - successCount} 个`);
            fetchTableData();
          }
        })
        .catch((error) => {
          console.error("批量删除失败:", error);
          ElMessage.error("批量删除失败，请稍后再试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>


